<?php
/**
 * ZIP压缩解压缩类库
 *
 * ZIP压缩解压缩处理统一封装
 *
 * @package Orz Framework Project
 * @author 纯粹误会<44922032@qq.com>
 * @version $Id: __zip.php 80 2010-02-21 16:06:39Z wujie $
 * @copyright (c) 2010, zh5j.com
 */
class_exists('FS', FALSE) || include (dirname(__FILE__) . '/fs.php');
class ZIP {
	
	/**
	 * 构造函数
	 * 
	 * 此函数完成ZIP扩展类的加载，以及压缩文件临时存储目录的创建工作
	 *
	 */
	public function __construct($zipdir) {
		class_exists ( 'PclZip', FALSE ) || include (dirname(__FILE__) . '/__zip/pclzip.lib.php');
		$this->_zipPath = $zipdir . '/' . date ( 'Ymd' );
		if (2 < date ( "h" )) {
			$dirs = FS::getDir ( $zipdir, 1, $this->_zipPath );
			if ($dirs) {
				FS::rm ( $dirs );
			}
		}
		FS::mkDir ( $this->_zipPath );
	}
	
	/**
	 * 压缩（支持目录和文件压缩）
	 *
	 * @param string $srcName 目录或单个文件
	 * @param string|array $fileLists 文件列表
	 * @param string $zipname 文件列表
	 * @return FALSE | string $zipname
	 */
	public function zip($srcName, $fileLists = NULL, $zipname = NULL) {
		if (is_null ( $zipname )) {
			$zipname = date ( 'YmdHis' ) . '.zip';
			$zipname = $this->_zipPath . '/' . $zipname;
			if (is_file ( $zipname )) {
				for($i = 0; $i < 10; $i ++) {
					$zipname = date ( 'YmdHis' ) . '_' . rand ( 10000000, 99999999 ) . '.zip';
					$zipname = $this->_zipPath . '/' . $zipname;
					if (! is_file ( $zipname )) {
						break;
					}
				}
				if (is_file ( $zipname )) {
					return FALSE;
				}
			}
		} elseif (is_file ( $zipname )) {
			FS::rm ( $zipname );
		}
		if (empty ( $fileLists )) {
			$fileLists = basename ( $srcName );
			$srcName = dirname ( $srcName );
		}
		if (is_dir ( $srcName )) {
			chdir ( $srcName );
		}
		$zip = new PclZip ( $zipname );
		$isOK = $zip->create ( $fileLists );
		if ($isOK) {
			return realpath ( $zipname );
		} else {
			return FALSE;
		}
	}
	
	/**
	 * 解压缩到指定目录
	 *
	 * @param string $zipname 欲解压缩的文件
	 * @param string $destpath 目标目录
	 * @return unknown
	 */
	public function unzip($zipname, $destpath = NULL) {
		if (! is_file ( $zipname )) {
			return FALSE;
		}
		if (is_null ( $destpath )) {
			$destpath = date ( 'YmdHis' );
			$destpath = $this->_zipPath . '/' . $destpath;
			if (file_exists ( $destpath )) {
				for($i = 0; $i < 10; $i ++) {
					$destpath = date ( 'YmdHis' ) . '_' . rand ( 10000000, 99999999 );
					$destpath = $this->_zipPath . '/' . $destpath;
					if (! file_exists ( $destpath )) {
						break;
					}
				}
				if (file_exists ( $destpath )) {
					return FALSE;
				}
			}
		}
		$zip = new PclZip ( $zipname );
		$isOK = $zip->extract (  ( $destpath ) );
		if ($isOK) {
			return realpath ( $destpath );
		} else {
			return FALSE;
		}
	}
}
?>